package net.maku.qdd.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import net.maku.qdd.common.utils.PageResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.maku.qdd.convert.TicketConvert;
import net.maku.qdd.entity.TicketEntity;
import net.maku.qdd.query.TicketQuery;
import net.maku.qdd.vo.TicketVO;
import net.maku.qdd.vo.TicketDetailVO;
import net.maku.qdd.dao.TicketDao;
import net.maku.qdd.dao.GoodsDao;
import net.maku.qdd.service.TicketService;
import net.maku.qdd.common.utils.ExcelUtils;
import net.maku.qdd.vo.TicketExcelVO;
import net.maku.qdd.entity.MerchantEntity;
import net.maku.qdd.entity.GoodsEntity;
import net.maku.qdd.dao.MerchantDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 优惠券
 *
 * @author MAKU babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
public class TicketServiceImpl extends ServiceImpl<TicketDao, TicketEntity> implements TicketService {

    @Autowired
    private MerchantDao merchantDao;

    @Autowired
    private GoodsDao goodsDao;

    @Override
    public PageResult<TicketVO> page(TicketQuery query) {
        IPage<TicketEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(TicketConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }





    @Override
    public TicketVO get(Long id) {
        TicketEntity entity = baseMapper.selectById(id);
        TicketVO vo = TicketConvert.INSTANCE.convert(entity);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(TicketVO vo) {
        TicketEntity entity = TicketConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TicketVO vo) {
        TicketEntity entity = TicketConvert.INSTANCE.convert(vo);

        updateById(entity);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);

    }



    @Override
    public void export() {
        List<TicketExcelVO> excelList = TicketConvert.INSTANCE.convertExcelList(list());
        ExcelUtils.excelExport(TicketExcelVO.class, "优惠券", null, excelList);
    }

    @Override
    public TicketVO getByTicketCode(Integer ticketCode) {
        LambdaQueryWrapper<TicketEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TicketEntity::getTicketCode, ticketCode);
        TicketEntity entity = baseMapper.selectOne(wrapper);
        return entity != null ? TicketConvert.INSTANCE.convert(entity) : null;
    }

    @Override
    public PageResult<TicketVO> searchByMerchantName(String merchantName, Integer page, Integer limit) {
        // 首先根据商家名称查询商家ID
        LambdaQueryWrapper<MerchantEntity> merchantWrapper = Wrappers.lambdaQuery();
        merchantWrapper.like(MerchantEntity::getMerchantName, merchantName);
        List<MerchantEntity> merchants = merchantDao.selectList(merchantWrapper);

        if (merchants.isEmpty()) {
            return new PageResult<>(new ArrayList<>(), 0L);
        }

        // 获取商家ID列表
        List<Integer> merchantIds = merchants.stream()
                .map(MerchantEntity::getMerchantId)
                .collect(Collectors.toList());

        // 根据商家ID查询优惠券
        LambdaQueryWrapper<TicketEntity> ticketWrapper = Wrappers.lambdaQuery();
        ticketWrapper.in(TicketEntity::getMerchantId, merchantIds);

        IPage<TicketEntity> pageParam = new Page<>(page, limit);
        IPage<TicketEntity> ticketPage = baseMapper.selectPage(pageParam, ticketWrapper);

        return new PageResult<>(TicketConvert.INSTANCE.convertList(ticketPage.getRecords()), ticketPage.getTotal());
    }

    /**
     * 获取分页对象
     */
    private IPage<TicketEntity> getPage(TicketQuery query) {
        return new Page<>(query.getCurrent(), query.getSize());
    }

    /**
     * 获取查询包装器
     */
    private LambdaQueryWrapper<TicketEntity> getWrapper(TicketQuery query){
        LambdaQueryWrapper<TicketEntity> wrapper = Wrappers.lambdaQuery();
        // 这里可以添加具体的查询条件
        return wrapper;
    }

    @Override
    public TicketDetailVO getDetailByTicketCode(Integer ticketCode) {
        // 查询优惠券
        LambdaQueryWrapper<TicketEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TicketEntity::getTicketCode, ticketCode);
        TicketEntity ticketEntity = this.getOne(wrapper);

        if (ticketEntity == null) {
            return null;
        }

        // 查询商家信息
        MerchantEntity merchantEntity = merchantDao.selectById(ticketEntity.getMerchantId());

        // 查询商品信息
        GoodsEntity goodsEntity = goodsDao.selectById(ticketEntity.getGoodsId());

        // 组装详细信息
        TicketDetailVO detailVO = new TicketDetailVO();

        // 优惠券信息
        detailVO.setTicketId(ticketEntity.getTicketId());
        detailVO.setTicketCode(ticketEntity.getTicketCode());
        detailVO.setPreferential(ticketEntity.getPreferential());
        detailVO.setLimitation(ticketEntity.getLimitation());
        detailVO.setDeadTime(ticketEntity.getDeadTime());
        detailVO.setEffectiveTime(ticketEntity.getEffectiveTime());

        // 商品信息
        if (goodsEntity != null) {
            detailVO.setGoodsId(goodsEntity.getGoodsId());
            detailVO.setGoodsName(goodsEntity.getGoodsName());
            detailVO.setGoodsPrice(goodsEntity.getGoodsPrice());
            detailVO.setGoodsNum(goodsEntity.getGoodsNum());
        }

        // 商家信息
        if (merchantEntity != null) {
            detailVO.setMerchantId(merchantEntity.getMerchantId());
            detailVO.setMerchantName(merchantEntity.getMerchantName());
            detailVO.setDirectorName(merchantEntity.getDirectorName());
            detailVO.setMerchantPhone(merchantEntity.getMerchantPhone());
            detailVO.setMerchantAdress(merchantEntity.getMerchantAdress());
            detailVO.setSigntime(merchantEntity.getSigntime());
        }

        return detailVO;
    }

    @Override
    public PageResult<TicketDetailVO> searchDetailByMerchantName(String merchantName, Integer page, Integer limit) {
        // 先查询商家
        LambdaQueryWrapper<MerchantEntity> merchantWrapper = Wrappers.lambdaQuery();
        merchantWrapper.like(MerchantEntity::getMerchantName, merchantName);
        List<MerchantEntity> merchants = merchantDao.selectList(merchantWrapper);

        if (merchants.isEmpty()) {
            return new PageResult<>(new ArrayList<>(), 0L);
        }

        // 获取商家ID列表
        List<Integer> merchantIds = merchants.stream()
                .map(MerchantEntity::getMerchantId)
                .collect(java.util.stream.Collectors.toList());

        // 分页查询优惠券
        Page<TicketEntity> ticketPage = new Page<>(page, limit);
        LambdaQueryWrapper<TicketEntity> ticketWrapper = Wrappers.lambdaQuery();
        ticketWrapper.in(TicketEntity::getMerchantId, merchantIds);
        ticketPage = this.page(ticketPage, ticketWrapper);

        // 转换为详细信息
        List<TicketDetailVO> detailList = new ArrayList<>();
        for (TicketEntity ticketEntity : ticketPage.getRecords()) {
            TicketDetailVO detailVO = new TicketDetailVO();

            // 优惠券信息
            detailVO.setTicketId(ticketEntity.getTicketId());
            detailVO.setTicketCode(ticketEntity.getTicketCode());
            detailVO.setPreferential(ticketEntity.getPreferential());
            detailVO.setLimitation(ticketEntity.getLimitation());
            detailVO.setDeadTime(ticketEntity.getDeadTime());
            detailVO.setEffectiveTime(ticketEntity.getEffectiveTime());

            // 查询并设置商品信息
            GoodsEntity goodsEntity = goodsDao.selectById(ticketEntity.getGoodsId());
            if (goodsEntity != null) {
                detailVO.setGoodsId(goodsEntity.getGoodsId());
                detailVO.setGoodsName(goodsEntity.getGoodsName());
                detailVO.setGoodsPrice(goodsEntity.getGoodsPrice());
                detailVO.setGoodsNum(goodsEntity.getGoodsNum());
            }

            // 查询并设置商家信息
            MerchantEntity merchantEntity = merchantDao.selectById(ticketEntity.getMerchantId());
            if (merchantEntity != null) {
                detailVO.setMerchantId(merchantEntity.getMerchantId());
                detailVO.setMerchantName(merchantEntity.getMerchantName());
                detailVO.setDirectorName(merchantEntity.getDirectorName());
                detailVO.setMerchantPhone(merchantEntity.getMerchantPhone());
                detailVO.setMerchantAdress(merchantEntity.getMerchantAdress());
                detailVO.setSigntime(merchantEntity.getSigntime());
            }

            detailList.add(detailVO);
        }

        return new PageResult<>(detailList, ticketPage.getTotal());
    }

    @Override
    public PageResult<TicketDetailVO> searchDetailByGoodsName(String goodsName, Integer page, Integer limit) {
        // 先查询商品
        LambdaQueryWrapper<GoodsEntity> goodsWrapper = Wrappers.lambdaQuery();
        goodsWrapper.like(GoodsEntity::getGoodsName, goodsName);
        List<GoodsEntity> goods = goodsDao.selectList(goodsWrapper);

        if (goods.isEmpty()) {
            return new PageResult<>(new ArrayList<>(), 0L);
        }

        // 获取商品ID列表
        List<Integer> goodsIds = goods.stream()
                .map(GoodsEntity::getGoodsId)
                .collect(java.util.stream.Collectors.toList());

        // 分页查询优惠券
        Page<TicketEntity> ticketPage = new Page<>(page, limit);
        LambdaQueryWrapper<TicketEntity> ticketWrapper = Wrappers.lambdaQuery();
        ticketWrapper.in(TicketEntity::getGoodsId, goodsIds);
        ticketPage = this.page(ticketPage, ticketWrapper);

        // 转换为详细信息
        List<TicketDetailVO> detailList = new ArrayList<>();
        for (TicketEntity ticketEntity : ticketPage.getRecords()) {
            TicketDetailVO detailVO = new TicketDetailVO();

            // 优惠券信息
            detailVO.setTicketId(ticketEntity.getTicketId());
            detailVO.setTicketCode(ticketEntity.getTicketCode());
            detailVO.setPreferential(ticketEntity.getPreferential());
            detailVO.setLimitation(ticketEntity.getLimitation());
            detailVO.setDeadTime(ticketEntity.getDeadTime());
            detailVO.setEffectiveTime(ticketEntity.getEffectiveTime());

            // 查询并设置商品信息
            GoodsEntity goodsEntity = goodsDao.selectById(ticketEntity.getGoodsId());
            if (goodsEntity != null) {
                detailVO.setGoodsId(goodsEntity.getGoodsId());
                detailVO.setGoodsName(goodsEntity.getGoodsName());
                detailVO.setGoodsPrice(goodsEntity.getGoodsPrice());
                detailVO.setGoodsNum(goodsEntity.getGoodsNum());
            }

            // 查询并设置商家信息
            MerchantEntity merchantEntity = merchantDao.selectById(ticketEntity.getMerchantId());
            if (merchantEntity != null) {
                detailVO.setMerchantId(merchantEntity.getMerchantId());
                detailVO.setMerchantName(merchantEntity.getMerchantName());
                detailVO.setDirectorName(merchantEntity.getDirectorName());
                detailVO.setMerchantPhone(merchantEntity.getMerchantPhone());
                detailVO.setMerchantAdress(merchantEntity.getMerchantAdress());
                detailVO.setSigntime(merchantEntity.getSigntime());
            }

            detailList.add(detailVO);
        }

        return new PageResult<>(detailList, ticketPage.getTotal());
    }
}